package com.ikingtech.framework.sdk.office.utils;

import cn.hutool.core.io.IoUtil;
import com.ikingtech.framework.sdk.office.model.vo.AffixFileVo;
import org.apache.commons.lang3.ObjectUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 自定义文件util
 *
 * @author lqb
 */
public class CustomFileUtil {
    private static final String[] PIC_SUFFIX_ARRAY = {"jpg", "JPG", "jpeg", "JPEG", "png", "PNG"};

    private CustomFileUtil() {
    }

    /**
     * 获取图片列表
     *
     * @author lqb
     * @since 2023/09/20
     */
    public static List<AffixFileVo> getPicList(List<AffixFileVo> fileList) {
        if (ObjectUtils.isEmpty(fileList)) {
            return new ArrayList<>();
        }
        return fileList.stream().filter(f -> Arrays.asList(PIC_SUFFIX_ARRAY).contains(f.getSuffix())).collect(Collectors.toList());
    }

    /**
     * 获取其他列表
     *
     * @author lqb
     * @since 2023/09/20
     */
    public static List<AffixFileVo> getOtherList(List<AffixFileVo> fileList) {
        if (ObjectUtils.isEmpty(fileList)) {
            return new ArrayList<>();
        }
        return fileList.stream().filter(f -> !Arrays.asList(PIC_SUFFIX_ARRAY).contains(f.getSuffix())).collect(Collectors.toList());
    }

    /**
     * 读取文件到字节
     *
     * @author lqb
     * @since 2023/09/25
     */
    public static byte[] readUrlFileToByte(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            //获取链接
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            //设置是否要从 URL 连接读取数据,默认为true
            uc.setDoInput(true);
            uc.connect();
            InputStream inputStream = uc.getInputStream();
            byte[] bytes = IoUtil.readBytes(inputStream);
            // 关闭流
            inputStream.close();
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
